import React, { useEffect, useState } from "react";
import Taro, { useRouter, useDidShow, usePullDownRefresh } from "@tarojs/taro";
import { View, Text, Input, Form, Button, Image } from "@tarojs/components";
import { GoodsItemData } from "@/components/GoodsItem/data";
import onPay from "@/common/utils/pay";
import createContract from "@/common/utils/createContract";
import phoneIcon from "@/images/phone_icon.png";
import IdIcon from "@/images/id_icon.png";
import contractIcon from "@/images/contract_icon.png";
// import { setData, getData } from "@/src/globalData";
// import FooterBtn from "@/components/FooterBtn";

import iconKefu from "@/images/order_icon_service.png";
import GoodsItem from "@/components/GoodsItem";
import yinzhangIcon from "@/images/icon_contract_left.png";
import "./index.scss";
import * as api from "./api";
import { OrderInfoData } from "./data";
import waitOpenToast from "@/src/common/utils/waitOpenToast";

const Index: React.FC<{}> = () => {
  const [goodsInfo, setGoodsInfo] = useState<
    GoodsItemData & { show_image: string; remark: string; quantity: number }
  >({});
  const [orderInfo, setOrderInfo] = useState<
    Partial<
      OrderInfoData & {
        payment_list: any[];
        despatch_type: string;
        id: number;
        status: string;
        last_payment_type: string;
      }
    >
  >({ order_item_list: [{}] });
  const router = useRouter();

  useDidShow(() => {
    getOrderInfo();
  });

  usePullDownRefresh(() => {
    getOrderInfo();
  });

  const getOrderInfo = async () => {
    try {
      Taro.showLoading();
      const { result, status } = await api.customer_order_get({
        order_id: router.params.order_id,
      });
      if (status === "ok") {
        setOrderInfo(result.order_info);
        setGoodsInfo(result.order_info.order_item_list[0]);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.stopPullDownRefresh();
      Taro.hideLoading();
    }
  };

  const payTypeMap = {
    wechat: "微信",
    bank: "银行卡支付",
    saobei: "扫呗",
    alipay: "支付宝",
    balance: "余额支付",
  };

  const despatch_type_map: any = {
    logistics: "物流",
    phone_top_up: "手机充值",
    eduction_contract: "教育合同",
  };

  const orderStatusMap: Record<string, string> = {
    order_launched: "待支付",
    payment_finished: "待发货",
    delivery_finished: "待收货",
    order_finished: "已完成",
    order_closed: "已取消",
  };

  const onCopy = () => {
    Taro.setClipboardData({
      data: String(orderInfo.number),
      success: () => {
        Taro.showToast({
          title: "复制成功",
        });
      },
    });
  };

  const goPayRecord = () => {
    Taro.navigateTo({
      url: `/pages/payRecord/index?params=${JSON.stringify({
        payment_list: orderInfo.payment_list,
        strike_price: orderInfo.strike_price,
        actual_amount: orderInfo.actual_amount,
      })}`,
    });
  };

  return (
    <View className="order-detail-page">
      <View className="status-con">{orderStatusMap[orderInfo.status]}</View>
      {orderInfo.invoice_info && (
        <View className="dispatch-info">
          <Image className="icon" src={yinzhangIcon} />
          {orderInfo.invoice_info.name ? (
            <View className="info">
              <View className="name">{orderInfo.invoice_info.name}</View>
              <View className="phone">
                <Text>{orderInfo.invoice_info.phone}</Text>
                <Image src={phoneIcon} mode="widthFix" />
              </View>
              <View className="identification">
                <Text>{orderInfo.invoice_info.identification}</Text>
                <Image src={IdIcon} mode="widthFix" />
              </View>
            </View>
          ) : (
            <View className="info">
              <View className="info-it">请填写签署人信息</View>
            </View>
          )}
        </View>
      )}

      <View className="info-card">
        <View className="title">报考信息</View>
        <GoodsItem
          className="goods-item"
          id={goodsInfo.id}
          thumbnail={goodsInfo.show_image}
          title={goodsInfo.title}
          school_name={goodsInfo.school_name}
          major_name={goodsInfo.major_name}
          duration={goodsInfo.duration}
          school_city={goodsInfo.school_city}
          production_name={goodsInfo.category}
          brand_name={goodsInfo.brand_name}
          sale_price={goodsInfo.sale_price}
          agent_name={goodsInfo.agent_name}
          category={goodsInfo.category}
          count={goodsInfo.quantity}
        />

        <View className="cate-info">
          属性：<Text>{goodsInfo.remark}</Text>
          发货：
          <Text>
            {despatch_type_map[orderInfo.order_item_list[0].despatch_type]}
          </Text>
        </View>

        {orderInfo.status === "order_finished" &&
          orderInfo.order_item_list[0]?.despatch_type ===
            "eduction_contract" && (
            <View
              className="btn"
              onClick={() => {
                createContract(orderInfo.order_item_list[0].contract_id, (contract_info) => {
                  Taro.navigateTo({
                    url: `/pages/contratPreview/index?params=${JSON.stringify(
                      contract_info
                    )}`,
                  });
                });
              }}
            >
              查看合同
            </View>
          )}

        {orderInfo.status === "delivery_finished" &&
          orderInfo.order_item_list[0]?.despatch_type ===
            "eduction_contract" && (
            <View
              className="btn"
              onClick={() => {
                createContract(orderInfo.order_item_list[0].contract_id, (contract_info) => {
                  const params = {
                    invoice_info: orderInfo.invoice_info,
                    contract_info,
                  };
                  Taro.navigateTo({
                    url: `/pages/signContract/index?params=${JSON.stringify(
                      params
                    )}`,
                  });
                });
              }}
            >
              签署合同
            </View>
          )}

        <View className="amount-info">
          <View className="item">
            <View className="label">助学原价</View>
            <View className="value">
              ￥{(orderInfo.sale_price / 100).toFixed(2)}
            </View>
          </View>
          <View className="item">
            <View className="label">优惠金额</View>
            <View className="value">
              -￥{(orderInfo.discount / 100).toFixed(2)}
            </View>
          </View>
          <View className="item">
            <View className="label">成交价</View>
            <View className="value">
              ￥{(orderInfo.strike_price / 100).toFixed(2)}
            </View>
          </View>
          <View className="item">
            <View className="label"></View>
            <View className="value">
              {orderInfo.arrears ? (
                <Text className="gray">
                  欠缴：{(orderInfo.arrears / 100).toFixed(2)}，
                </Text>
              ) : null}
              {orderInfo.status === "order_launched" ||
              orderInfo.status === "order_closed" ? (
                <Text className="actul">
                  <Text>需付款：</Text>
                  <Text className="num">
                    {" "}
                    ￥{(orderInfo.deposit / 100).toFixed(2)}
                  </Text>
                </Text>
              ) : (
                <Text className="actul">
                  <Text>实付款：</Text>
                  <Text className="num">
                    {" "}
                    ￥{(orderInfo.actual_amount / 100).toFixed(2)}
                  </Text>
                </Text>
              )}
            </View>
          </View>
        </View>
      </View>
      <View className="order-info">
        <View className="sub-title">订单信息</View>
        <View className="order-info-it">
          <View className="label">订单编号</View>
          <View className="value">{orderInfo.number}</View>
          <View className="tag" onClick={onCopy}>
            复制
          </View>
        </View>
        <View className="order-info-it">
          <View className="label">下单时间</View>
          <View className="value">{orderInfo.create_time}</View>
        </View>

        {/* <View className="order-info-it">
          <View className="label">成交价</View>
          <View className="value">
            ￥{(orderInfo.strike_price / 100).toFixed(2)}
          </View>
        </View> */}

        <View className="order-info-it">
          <View className="label">支付方式</View>
          <View className="value">{orderInfo.pay_services}</View>
        </View>
      </View>

      {orderInfo.status !== "order_launched" &&
        orderInfo.status !== "order_closed" && (
          <View className="order-info lr">
            <View className="sub-title">
              <Text>付款信息</Text>
              <Text onClick={() => goPayRecord()}>查询付款记录 {">>"} </Text>
            </View>
            <View className="order-info-it">
              <View className="label">付款方式</View>
              <View className="value">
                {payTypeMap[orderInfo.last_payment_type]}
              </View>
            </View>
            <View className="order-info-it">
              <View className="label">付款单号</View>
              <View className="value">{orderInfo.last_payment_number}</View>
            </View>
            <View className="order-info-it">
              <View className="label">付款时间</View>
              <View className="value">{orderInfo.last_payment_time}</View>
            </View>
            <View className="order-info-it">
              <View className="label">付款金额</View>
              <View className="value">
                ￥{(orderInfo.last_payment_amount / 100).toFixed(2)}
              </View>
            </View>
          </View>
        )}

      <View className="blank"></View>
      <View className="footer-content">
        <View className="l">
          <View className="item" onClick={waitOpenToast}>
            <Image className="icon" src={iconKefu} />
            <Text>客服</Text>
          </View>
        </View>
        {orderInfo.status === "order_launched" && (
          <View className="r">
            <View
              className="button"
              onClick={() => {
                onPay(orderInfo.id, () => {
                  getOrderInfo();
                });
              }}
            >
              立即支付
            </View>
          </View>
        )}
      </View>
    </View>
  );
};

export default Index;
